package com.lingz.manager.modules.wuxue.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingz.manager.modules.wuxue.entity.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Classname DeviceDataUtil
 * @Description TODO
 * @Date 2023/11/30 10:57
 * @Created by mjh
 */
public class DeviceDataUtil {
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
    public static HuangshiData parseJsonToHSWeatherData(JSONObject jsonObject) throws ParseException {
        HuangshiData huangshiData = new HuangshiData();
        String collectTimeS = jsonObject.getString("collectTime");
        Date collectTime = sdf.parse(collectTimeS);
        Long uploadTimeS = jsonObject.getLong("uploadTime");
        Instant instant = Instant.ofEpochMilli(uploadTimeS); // 转换为 Instant
        Date uploadTime = Date.from(instant); // 转换为旧版的 Date
        String deviceId = jsonObject.getJSONObject("device").getString("id");
        Double dianChiDianYa = jsonObject.getDouble("dianChiDianYa");
        Double fiftyTuRangHanShuiLiang = jsonObject.getDouble("fiftyTuRangHanShuiLiang");
        Double fiftyTuRangWenDu = jsonObject.getDouble("fiftyTuRangWenDu");
        Double fiveTuRangHanShuiLiang = jsonObject.getDouble("fiveTuRangHanShuiLiang");
        Double fiveTuRangWenDu = jsonObject.getDouble("fiveTuRangWenDu");
        String dataId = jsonObject.getString("id");
        Double kongQiWenDu = jsonObject.getDouble("kongQiWenDu");
        Double luDianWenDu = jsonObject.getDouble("luDianWenDu");
        Double riZhaoShiShu = jsonObject.getDouble("riZhaoShiShu");
        Double shiRunShiJian = jsonObject.getDouble("shiRunShiJian");
        Double tenTuRangHanShuiLiang = jsonObject.getDouble("tenTuRangHanShuiLiang");
        Double tenTuRangWenDu = jsonObject.getDouble("tenTuRangWenDu");
        Double tianJiangYuLiang = jsonObject.getDouble("tianJiangYuLiang");
        Double tuRangDaoDianLv = jsonObject.getDouble("tuRangDaoDianLv");
        Double twentyFiveTuRangHanShuiLiang = jsonObject.getDouble("twentyFiveTuRangHanShuiLiang");
        Double twentyFiveTuRangWenDu = jsonObject.getDouble("twentyFiveTuRangWenDu");
        Double twentyTuRangHanShuiLiang = jsonObject.getDouble("twentyTuRangHanShuiLiang");
        Double twentyTuRangWenDu = jsonObject.getDouble("twentyTuRangWenDu");
        Double xiangDuiShiDu = jsonObject.getDouble("xiangDuiShiDu");
        Double xiaoShiJiangYuLiang = jsonObject.getDouble("xiaoShiJiangYuLiang");
        // 设置设备id
        huangshiData.setCollectTime(collectTime);
        huangshiData.setUploadTime(uploadTime);
        huangshiData.setDianChiDianYa(dianChiDianYa);
        huangshiData.setFiftyTuRangHanShuiLiang(fiftyTuRangHanShuiLiang);
        huangshiData.setFiftyTuRangWenDu(fiftyTuRangWenDu);
        huangshiData.setFiveTuRangHanShuiLiang(fiveTuRangHanShuiLiang);
        huangshiData.setTenTuRangWenDu(tenTuRangWenDu);
        huangshiData.setFiveTuRangWenDu(fiveTuRangWenDu);
        huangshiData.setDataId(dataId);
        huangshiData.setKongQiWenDu(kongQiWenDu);
        huangshiData.setLuDianWenDu(luDianWenDu);
        huangshiData.setTwentyTuRangHanShuiLiang(twentyTuRangHanShuiLiang);
        huangshiData.setTwentyTuRangWenDu(twentyTuRangWenDu);
        huangshiData.setXiangDuiShiDu(xiangDuiShiDu);
        huangshiData.setXiaoShiJiangYuLiang(xiaoShiJiangYuLiang);
        huangshiData.setRiZhaoShiShu(riZhaoShiShu);
        huangshiData.setShiRunShiJian(shiRunShiJian);
        huangshiData.setTenTuRangHanShuiLiang(tenTuRangHanShuiLiang);
        huangshiData.setTianJiangYuLiang(tianJiangYuLiang);
        huangshiData.setTuRangDaoDianLv(tuRangDaoDianLv);
        huangshiData.setTwentyFiveTuRangHanShuiLiang(twentyFiveTuRangHanShuiLiang);
        huangshiData.setTwentyFiveTuRangWenDu(twentyFiveTuRangWenDu);
        huangshiData.setDeviceId(deviceId);
        return huangshiData;
    }

    public static YikemanData parseJsonToYKMInsectData(JSONObject jsonObject) throws ParseException {
        YikemanData yikemanData = new YikemanData();
        String endDateS = jsonObject.getString("endDate");
        Date endDate = sdf2.parse(endDateS);
        String startDateS = jsonObject.getString("startDate");
        Date startDate = sdf2.parse(startDateS);
        String createDateS = jsonObject.getString("createDate");
        Date createDate = sdf.parse(createDateS);
        Long sendMsmDateS = jsonObject.getLong("sendMsmDate");
        Instant instant = Instant.ofEpochMilli(sendMsmDateS); // 转换为 Instant
        Date sendMsmDate = Date.from(instant); // 转换为旧版的 Date
        String locationName = jsonObject.getString("locationName");
        String pestTypeId = jsonObject.getString("pestTypeId");
        Long pestNum = jsonObject.getLong("pestNum");
        String deviceId = jsonObject.getString("deviceId");
        String definiteAddress = jsonObject.getString("definiteAddress");
        String cnName = jsonObject.getString("cnName");
        Double temperature = jsonObject.getDouble("temperature");
        Double humidity = jsonObject.getDouble("humidity");
        String id = jsonObject.getString("id");
        String modelSerail = jsonObject.getString("modelSerail");
        ///
        yikemanData.setDataId(id);
        yikemanData.setDeviceId(deviceId);
        yikemanData.setHumidity(humidity);
        yikemanData.setCnName(cnName);
        yikemanData.setDefiniteAddress(definiteAddress);
        yikemanData.setPestNum(pestNum);
        yikemanData.setPestTypeId(pestTypeId);
        yikemanData.setLocationName(locationName);
        yikemanData.setTemperature(temperature);
        yikemanData.setModelSerail(modelSerail);
        yikemanData.setEndDate(endDate);
        yikemanData.setStartDate(startDate);
        yikemanData.setCreateDate(createDate);
        yikemanData.setSendMsmDate(sendMsmDate);
        return yikemanData;
    }

    public static TuopuInsectData parseJsonToTPInsectData(JSONObject jsonObject,String deviceId) throws ParseException {
        // list下的img_list下的每一项作为一条记录
        TuopuInsectData tuopuInsectData = new TuopuInsectData();
        String imgId = jsonObject.getString("img_id");
        String imgUrl = jsonObject.getString("img_url");
        String imgTimeS = jsonObject.getString("img_time");
        Date imgTime = sdf.parse(imgTimeS);
        JSONArray insects = jsonObject.getJSONArray("insect");
        if(insects != null && !insects.isEmpty()) {
            JSONObject insect = insects.getJSONObject(0);
            Long insectNumber = insect.getLong("number");
            String insectTypeId = insect.getString("insect_type_id");
            JSONArray features = insect.getJSONArray("feature");
            if(features != null && !features.isEmpty()) {
                JSONObject feature = features.getJSONObject(0);
                String featureX = feature.getString("x");
                String featureY = feature.getString("y");
                ////
                tuopuInsectData.setFeatureX(featureX);
                tuopuInsectData.setFeatureY(featureY);
            }
            ////
            tuopuInsectData.setInsectNumber(insectNumber);
            tuopuInsectData.setInsectTypeId(insectTypeId);

        }
        ////
        tuopuInsectData.setImgId(imgId);
        tuopuInsectData.setImgUrl(imgUrl);
        tuopuInsectData.setImgTime(imgTime);
        tuopuInsectData.setDeviceId(deviceId);
        return tuopuInsectData;

    }

    public static String createTPUrl(String term_type, String serial_nums, String start_date, String end_date) {
        // 1. 确定参数
        String method = "termData";
        String format = "json";
        String version = "v1.0";
        String app_key = "drczvzhfoapn";
        String appSecret = "23SxNccRVdiGeH8M";
        // 2. 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = now.format(formatter);
        // 3. 参数进行MD5加密构建sign
        String originSignature = appSecret +
                "app_key" + app_key +
                "end_date" + end_date +
                "format" + format +
                "method" + method +
                "serial_nums" + serial_nums +
                "start_date" + start_date +
                "term_type" + term_type +
                "timestamp" + timestamp +
                "version" + version +
                appSecret;
        String sign = "";
        // 创建MessageDigest对象，并指定使用MD5算法
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");// 将输入字符串转换为字节数组
            byte[] inputBytes = originSignature.getBytes();
            // 使用MessageDigest对象对字节数组进行加密
            byte[] hashedBytes = md.digest(inputBytes);

            // 将加密后的字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashedBytes.length; i++) {
                sb.append(Integer.toString((hashedBytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            // 将加密后的字符串转换为大写形式
            sign = sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        // 4. 生成url
        return "https://open.topyn.cn/openapi?"+
                "app_key="+app_key+"&"+
                "version=v1.0&"+
                "format=json&"+
                "method=termData&"+
                "timestamp="+timestamp+"&"+
                "sign="+sign+"&"+
                "term_type="+term_type+"&"+
                "serial_nums="+serial_nums+"&"+
                "start_date="+start_date+"&"+
                "end_date=" + end_date;
    }

    public static WaterDeviceInfo parseJsonToWaterDeviceData(JSONObject jsonObject) throws ParseException {
        WaterDeviceInfo waterDeviceInfo = new WaterDeviceInfo();
        String installDateS = jsonObject.getString("installDate");
        Date installDate = sdf3.parse(installDateS);
        Long id = jsonObject.getLong("id");
        String stname = jsonObject.getString("stname");
        String stcd = jsonObject.getString("stcd");
        String stakeNum = jsonObject.getString("stakeNum");
        Long category = jsonObject.getLong("category");
        String categoryLable = jsonObject.getString("categoryLable");
        Long canal = jsonObject.getLong("canal");
        String canalLable = jsonObject.getString("canalLable");
        String coordinate = jsonObject.getString("coordinate");
        Long photo = jsonObject.getLong("photo");
        String onLine = jsonObject.getString("onLine");

        waterDeviceInfo.setId(id);
        waterDeviceInfo.setInstallDate(installDate);
        waterDeviceInfo.setStname(stname);
        waterDeviceInfo.setStcd(stcd);
        waterDeviceInfo.setStakeNum(stakeNum);
        waterDeviceInfo.setCategory(category);
        waterDeviceInfo.setCategoryLable(categoryLable);
        waterDeviceInfo.setCanal(canal);
        waterDeviceInfo.setCanalLable(canalLable);
        waterDeviceInfo.setCoordinate(coordinate);
        waterDeviceInfo.setPhoto(photo);
        waterDeviceInfo.setOnline(onLine);
        return waterDeviceInfo;
    }

    public static WaterConservancyData parseJsonToWaterConservancyData(JSONObject jsonObject, String stname) throws ParseException {
        WaterConservancyData waterConservancyData = new WaterConservancyData();
        String tmS = jsonObject.getString("tm");
        if(tmS == null) return null;
        Date tm = sdf.parse(tmS);
        String stcd = jsonObject.getString("stcd");
        Double q = jsonObject.getDouble("q");
        Double qa = jsonObject.getDouble("qa");
        Double qaToday = jsonObject.getDouble("qaToday");
        Double qaDay = jsonObject.getDouble("qaDay");
        Double qaMonth = jsonObject.getDouble("qaMonth");
        Double qaSum = jsonObject.getDouble("qaSum");
        Double vj = jsonObject.getDouble("vj");
        Double rqa = jsonObject.getDouble("rqa");
        Double z = jsonObject.getDouble("z");
        Double gh = jsonObject.getDouble("gh");
        Double vt = jsonObject.getDouble("vt");

        waterConservancyData.setStcd(stcd);
        waterConservancyData.setStname(stname);
        waterConservancyData.setTm(tm);
        waterConservancyData.setQ(q);
        waterConservancyData.setQa(qa);
        waterConservancyData.setQaToday(qaToday);
        waterConservancyData.setQaDay(qaDay);
        waterConservancyData.setQaMonth(qaMonth);
        waterConservancyData.setQaSum(qaSum);
        waterConservancyData.setVj(vj);
        waterConservancyData.setRqa(rqa);
        waterConservancyData.setZ(z);
        waterConservancyData.setGh(gh);
        waterConservancyData.setVt(vt);

        return waterConservancyData;
    }

    public static HtjrDeviceInfo parseJsonToHtjrDeviceInfoData(JSONObject jsonObject) {
        HtjrDeviceInfo htjrDeviceInfo = new HtjrDeviceInfo();
        Long id = jsonObject.getLong("id");
        Long deptId = jsonObject.getLong("deptId");
        String equipmentType = jsonObject.getString("equipmentType");
        Long equipmentTypeId = jsonObject.getLong("equipmentTypeId");
        Integer groupNo = jsonObject.getInteger("groupNo");
        String installAddress = jsonObject.getString("installAddress");
        String siteName = jsonObject.getString("siteName");
        String x = jsonObject.getString("x");
        String y = jsonObject.getString("y");

        htjrDeviceInfo.setId(id);
        htjrDeviceInfo.setDeptId(deptId);
        htjrDeviceInfo.setEquipmentType(equipmentType);
        htjrDeviceInfo.setEquipmentTypeId(equipmentTypeId);
        htjrDeviceInfo.setGroupNo(groupNo);
        htjrDeviceInfo.setInstallAddress(installAddress);
        htjrDeviceInfo.setSiteName(siteName);
        htjrDeviceInfo.setLat(x);
        htjrDeviceInfo.setLng(y);

        return htjrDeviceInfo;
    }
}
